#pragma once

#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>
#include <fstream>
#include <cassert>
#include <mysql/mysql.h>

#include "../comm/log.hpp"
#include "../comm/util.hpp"

using std::string;

namespace ns_model
{
    using namespace ns_log;
    using namespace ns_util;

    typedef struct Question
    {
        /* data */
        string number;     // 题目编号
        string title;      // 题目标题
        string difficulty; // 题目难度
        string desc;       // 题目描述
        string header;     // 题目预设代码
        string tail;       // 测试用例
        int cpu_limit;     // 时间要求(sec)
        int mem_limit;     // 空间要求(KB)
    } Question;

    const string oj_questions = "oj_questions";
    const string host = "127.0.0.1";
    const string user = "oj_client";
    const string pwd = "123456";
    const string db = "oj";
    const int port = 3306;

    class Model
    {
    private:
        std::unordered_map<string, Question> questions;

    public:
        Model() {}
        ~Model() {}
        bool QueryMySql(const string &sql, std::vector<Question> *out)
        {
            MYSQL *conn = mysql_init(nullptr);

            if (nullptr == mysql_real_connect(conn, host.c_str(), user.c_str(), pwd.c_str(), db.c_str(), port, nullptr, 0))
            {
                // 连接失败
                LOG(FATAL) << "连接数据库失败\n";
                return false;
            }
            mysql_set_character_set(conn, "utf8");
            if (0 != mysql_query(conn, sql.c_str()))
            {
                // 查询失败
                LOG(WARNING) << sql << "执行错误\n";
            }
            // 分析结果
            MYSQL_RES *res = mysql_store_result(conn);
            int rows = mysql_num_rows(res);

            Question q;

            for (int i = 0; i < rows; i++)
            {
                MYSQL_ROW row = mysql_fetch_row(res);
                q.number = row[0];
                q.title = row[1];
                q.difficulty = row[2];
                q.desc = row[3];
                q.header = row[4];
                q.tail = row[5];
                q.cpu_limit = atoi(row[6]);
                q.mem_limit = atoi(row[7]);

                out->push_back(q);
            }

            mysql_free_result(res);
            mysql_close(conn);
            return true;
        }
        bool GetAllQuestions(std::vector<Question> *out)
        {
            string sql = "select * from ";
            sql += oj_questions;
            return QueryMySql(sql,out);
        }
        bool GetNumQuestion(const string &number, Question *q)
        {
            string sql = "select * from ";
            sql += oj_questions;
            sql += " where number =  ";
            sql += number;
            std::vector<Question> out;
            if(QueryMySql(sql,&out))
            {
                *q = out[0];
                return true;
            }
            return false;
        }
    };
}